<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <div id="searchDIV"></div>
      <table class="layui-table" id="finishedOrderTable" lay-filter="finishedOrderTable"></table>
    </div>
  </div>
</div>
<!-- 搜查条件框-->
<script type="text/html" id="searchContent">
  <div class="layui-form lay-header">
    <div class="toolbar">
      <div class="layui-form-item lay-query-content" style="height: auto;width: auto">
        <div class="lay-query-box">
          <div class="query-lt">
            <div class="layui-inline ">
              <label class="layui-form-label">客户名称：</label>
              <div class="layui-input-inline ">
                <input class="layui-input" name="customerName" placeholder="请输入客户名称" lay-filter="customerName" />
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label w-auto">订单编号：</label>
              <div class="layui-input-inline ">
                <input class="layui-input" name="selCode" placeholder="请输入订单编号" lay-filter="selCode" />
              </div>
            </div>
            <div class="layui-inline">
              <div class="layui-input-inline">
                <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
              </div>
            </div>
          </div>
        </div>
        <!--                <div class="lay-search-box" style="border-bottom: 1px solid #EAEDF3">-->
        <!--                  -->
        <!--                </div>-->
      </div>
    </div>
    <div class="lay-btn-rows">
      <div class="lay-btn-box">
        <div class="lay-btn-lt">
          <button id="contractBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
          <button id="configFun" style="display: none;" class="layui-btn icon-btn color-reseda" type="button">确认选择</button>
        </div>
        <div class="lay-btn-rt"></div>
      </div>
    </div>
  </div>
</script>
<!--退货状态(1.待审核 ，2已完成)-->

<script type="text/html" id="finishedOrderTableBar">
  <!-- {{# if(d.selStatusName=='待提交'){ }} -->
  <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="submit">提交</button>
  <button class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</button>
  <!-- {{# } }} -->
  <!-- {{# if(d.selStatusName=='待审核'){ }} -->
  <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="audit">审核</button>
  <!-- {{# } }} -->
  <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">详情</button>

  <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
  <button class="layui-btn  layui-btn-xs" lay-event="plan">计划生产</button>
  <button class="layui-btn  layui-btn-xs" lay-event="print">打印</button>
</script>
<!--打印销售弹窗-->
<script type="text/html" id="printFinishedOrderTemplate">
  <form lay-filter="printFinishedOrderTemplateForm" class="layui-form open-form printTemplateForm">
    <div class="open-model">
      <div class="open-auto">
        <div class="my-print-box" id="printHtml">

        </div>
      </div>
      <div class="layui-form-item text-right">
        <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        <button class="layui-btn" type="button" id="printPurchaseOrder">打印</button>
      </div>
    </div>
  </form>
</script>
<script src="/admin/assets/libs/jquery/jquery-3.2.1.min.js"></script>
<script src="/admin/assets/libs/jquery/jQuery.print.js.js"></script>
<script>
  layui.use(["layer", "form", "table", "admin", "upload", "tree", "laytpl", "laydate"], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    var laytpl = layui.laytpl;
    var laydate = layui.laydate;
    var syncProductName = "";
    var syncProductId = 0;
    let nowData = {};
 
    laytpl(searchContent.innerHTML).render({}, function (html) {
      $("#searchDIV").html(html);
      form.render("select");
    });
    if (typeof parentData !== "undefined") {
      nowData = { ...parentData };
      if (nowData.eventName == "radio" || nowData.eventName == "checkbox") {
        $("#configFun").show();
      }
    }
    table.render({
      elem: "#finishedOrderTable",
      url: config.base + "enterprise/sell/admin/finishedOrder/list",
      page: true,
      cols: [
        [
          { type: "radio", hide: nowData.eventName == "radio" ? false : true },
          { type: "numbers", align: "center", title: "序号" },
          { field: "selCode", align: "center", title: "订单编号" },
          { field: "selTypeName", align: "center", title: "订单类型" },
          { field: "customerTypeName", align: "center", title: "客户类型" },
          { field: "customerName", align: "center", title: "客户名称" },
          { field: "skuQuantity", align: "center", title: "产品数量" },
          { field: "totalMoney", align: "center", title: "金额" },
          // {field: 'creatorName', align: 'center',title: '添加人'},
          // {field: 'createTime', align: 'center',title: '添加时间'},
          { field: "auditName", align: "center", title: "审核人" },
          { field: "auditTime", align: "center", title: "审核时间" },
          { field: "selStatusName", align: "center", title: "订单状态" },
          { field: "createTime", align: "center", title: "创建时间" },
          {
            align: "center",
            toolbar: "#finishedOrderTableBar",
            title: "操作",
            fixed: "right",
            width: 370
          }
        ]
      ]
    });
    $("#contractBtnAdd").click(function () {
      openForm("add");
    });
    $("#configFun").click(function () {
      let list = table.checkStatus("finishedOrderTable").data;
      childData.list = list.map((v) => {
        v.code = v.selCode;
        return v;
      });
      layer.close(nowData.zindex);
    });
    form.on("submit(formSubSearchLog)", function (data) {
      table.reload("finishedOrderTable", {
        where: data.field
      });
    });
    form.on("submit(resets)", function (data) {
      table.reload("finishedOrderTable", {
        where: admin.resetSearch(data.field)
      });
    });

    function openForm(event, data) {
      const titles = {
        add: "添加成品销售订单",
        detail: `查看成品销售订单`,
        edit: `编辑成品销售订单`
      };
      admin.formOpen({
        area: ["85%", "85%"],
        offset: "50px",
        title: titles[event],
        path: "components/sell/finishedOrderForm.html",
        success: function () {
          parentData.eventName = event;
          parentData.data = data;
        }
      });
    }

    table.on("tool(finishedOrderTable)", function (obj) {
      var data = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      if (layEvent === "detail") {
        admin.req("enterprise/sell/admin/finishedOrder/detail/" + data.id, {}, function (res) {
          if (res.code == 200) {
            openForm(layEvent, res.data);
          }
        });
      } else if (layEvent === "edit") {
        // 点击编辑按钮
        admin.req("enterprise/sell/admin/finishedOrder/detail/" + data.id, {}, function (res) {
          if (res.code == 200) {
            openForm(layEvent, res.data);
          }
        });
      } else if (layEvent === "del") {
        // 点击编辑按钮
        layer.confirm(
          "是否确认删除",
          {
            offset: "65px",
            skin: "layui-layer-admin"
          },
          function () {
            admin.req(
              "enterprise/sell/admin/finishedOrder/delete/" + data.id,
              {},
              function (res) {
                if (res.code == 200) {
                  layer.msg("删除成功");
                  table.reload("finishedOrderTable");
                } else {
                  layer.msg("删除失败");
                }
              },
              "DELETE"
            );
          }
        );
      } else if (layEvent === "submit") {
        layer.confirm(
          "是否确认提交",
          {
            offset: "65px",
            skin: "layui-layer-admin"
          },
          function () {
            admin.req(
              "enterprise/sell/admin/finishedOrder/submit/" + data.id,
              {},
              function (res) {
                if (res.code == 200) {
                  layer.msg("提交成功");
                  table.reload("finishedOrderTable");
                } else {
                  layer.msg("提交失败");
                }
              },
              "POST"
            );
          }
        );
      } else if (layEvent === "audit") {
        layer.confirm(
          "是否确认审核",
          {
            offset: "65px",
            skin: "layui-layer-admin"
          },
          function () {
            admin.req(
              "enterprise/sell/admin/finishedOrder/audit/" + data.id,
              {},
              function (res) {
                if (res.code == 200) {
                  layer.msg("审核成功");
                  table.reload("finishedOrderTable");
                } else {
                  layer.msg("审核失败");
                }
              },
              "POST"
            );
          }
        );
      } else if (obj.event === "plan") {
        admin.formOpen({
          type: 1,
          area: ["85%", "80%"],
          title: "添加生产计划",
          path: "components/productionPlan/productionPlanForm.html",
          success: function () {
            console.log(data);
            parentData.eventName = "add";
            parentData.planSourceType = "finish";
            parentData.orderId = data.id;
            parentData.orderCode = data.selCode;
          }
        });
      } else if (obj.event === 'print') {
        showPrintFinishedOrderTemplate(data);
      }
    });
    // 打印采购单
    function showPrintFinishedOrderTemplate(data) {
      admin.open({
        type: 1,
        area: ["1060px", "800px"],
        offset: '65px',
        title: '销售订单',
        content: $('#printFinishedOrderTemplate').html(),
        success: function () {
          let html = "";
          admin.req("enterprise/sell/admin/finishedOrder/detail/" + data.id, {}, function (res) {
            if (res.code === 200) {
              let orderItem = res.data;
              let customerObj = {}, auditName = '';
              admin.reqSync("enterprise/sell/admin/contactInfo/list", {selCustomerId: res.data.customerId}, function (obj) {
                if (obj.code == 200) {
                  customerObj = obj.data.length > 0 ? obj.data[0] : {};
                }
              });
              // 获取审核人
              admin.reqSync("user/admin/user/list", {limit: 9999}, function (obj) {
                if (obj.code == 200) {
                  auditName = obj.data.find(v => v.id === res.data.auditId).name || '';
                }
              });
              html += `<div class="print-title">销售单</div>
          <div class="flexCt print-tip-info">
            <div class="company">公司：${config.getTempData('companyName')}</div>
            <div class="time">${orderItem.createTime}</div>
          </div>
          <div class="print-table">
            <div class="print-view">
              <div class="print-nape ">
                <div class="cell">
                  <div class="name w-120 justify">客户名称：</div>
                  <div class="val flex-1">${data.customerName}</div>
                </div>
                <div class="cell">
                  <div class="name w-120">联系人：</div>
                  <div class="val flex-1">${customerObj.name}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell">
                  <div class="name w-120">电话：</div>
                  <div class="val flex-1">${customerObj.telephone}</div>
                </div>
                <div class="cell">
                  <div class="name w-120">销售单号：</div>
                  <div class="val flex-1">${orderItem.selCode}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell">
                  <div class="name w-120">销售类型：</div>
                  <div class="val flex-1">${orderItem.selTypeName}</div>
                </div>
                <div class="cell">
                  <div class="name w-120">交货时间：</div>
                  <div class="val flex-1">${orderItem.planOnTime}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell w-100">
                  <div class="th v-60" style="padding: 0">序号</div>
                  <div class="th v-160">物料名称</div>
                  <div class="th v-160">物料编号</div>
                  <div class="th v-160">规格型号</div>
                  <div class="th" style="width: 11%;">产品类型</div>
                  <div class="th" style="width: 9%;">单位</div>
                  <div class="th">数量</div>
                  <div class="th">单价</div>
                  <div class="th">总价</div>
                </div>
              </div>`;
              let list = orderItem.details.length > 17 ? orderItem.details.slice(0, 17) : orderItem.details;
              let fillValue = {}, allMoney = new Decimal(0);
              let filledArray = [...list, ...Array.from({ length: 17 - list.length }, () => fillValue)];
              filledArray.forEach((item, index) => {
                if (item.totalMoney) {
                  allMoney = allMoney.add(new Decimal(item.totalMoney))
                }
                html += `<div class="print-nape">
                    <div class="cell w-100">
                      <div class="td v-60" style="padding: 0">${index + 1}</div>
                      <div class="td v-160">${item.skuName || ''}</div>
                      <div class="td v-160">${item.skuCode || ''}</div>
                      <div class="td v-160">${item.skuSpec || ''}</div>
                      <div class="td" style="width: 11%;">${item.productTypeName || ''}</div>
                      <div class="td" style="width: 9%;">${item.mainUnitName || ''}</div>
                      <div class="td">${item.selQuality || ''}</div>
                      <div class="td">${item.price != undefined ? item.price : ''}</div>
                      <div class="td">${item.totalMoney || ''}</div>
                    </div>
                  </div>`
              });
              html += `<div class="print-nape">
                <div class="cell w-100">
                  <div class="name w-120">合计：</div>
                  <div class="val flex-1 lt">人民币：${allMoney.toFixed(2)}</div>
                </div>
              </div>
              <div class="print-nape nape-btm">
                <div class="btm-sign lt">负责人签名与盖公司印章：</div>
                <div class="sign-rt flex-1">
                  <div class="cell w-100">
                    <div class="name flex-1">销售员</div>
                    <div class="name flex-1">审核人</div>
                  </div>
                  <div class="cell w-100">
                    <div class="val flex-1">${orderItem.creatorName}</div>
                    <div class="val flex-1">${auditName}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>`
              $('#printHtml').html(html);

              $("#printPurchaseOrder").click(function () {
                $('#printHtml').print({
                  debug: false,
                  importCSS: true,
                  printContainer: true,
                  operaSupport: false
                });
              })
            }
          });
        }
      })
    }
  });
</script>
